package httppojo

import (
	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/util"
	"log"
)

var DB *leveldb.DB

func init() {
	db, err := leveldb.OpenFile(CONFIG.Get("LEVEL_DB_PATH"), nil)
	if err != nil {
		log.Fatal(err.Error())
	}
	DB = db
}

func operate2(operate func(db *leveldb.DB) []string) []string {
	return operate(DB)
}

func operate(operate func(db *leveldb.DB) string) string {
	return operate(DB)
}

type Leveldb struct {
}

func NewLeveldb() *Leveldb {
	return &Leveldb{}
}

func (*Leveldb) Set(key string, value string) {
	operate(func(db *leveldb.DB) string {
		db.Put([]byte(key), []byte(value), nil)
		return ""
	})
}

func (*Leveldb) Get(key string) string {
	return operate(func(db *leveldb.DB) string {
		val, err := db.Get([]byte(key), nil)
		if err != nil {
			log.Println("get[" + key + "]" + err.Error())
			return ""
		} else {
			return string(val)
		}
	})
}

func (*Leveldb) Del(key string) string {
	return operate(func(db *leveldb.DB) string {
		err := db.Delete([]byte(key), nil)
		if err != nil {
			log.Println("Del[" + key + "]" + err.Error())
		}
		return key
	})
}

func (*Leveldb) Scan(key string) []string {
	return operate2(func(db *leveldb.DB) []string {
		var res []string
		iter := db.NewIterator(util.BytesPrefix([]byte(key)), nil)
		for iter.Next() {
			res = append(res, string(iter.Value()))
		}
		iter.Release()
		return res
	})
}

var LevelDb = NewLeveldb()
